package cp3120.dao.mysql;

import cp3120.dao.VariableDAO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Adam Scarr <scarr.adam@gmail.com>
 */
public class MySQLVariableDAO extends VariableDAO {
    private Connection db;
    private PreparedStatement getVariable;
    private PreparedStatement setVariable;

    /**
     * constructor, takes a database connection and calls private member to prepare the My SQL statements.
      * @param db the database that will be accessed
     */
    public MySQLVariableDAO(Connection db) {
        this.db = db;
        prepareStatements();
    }

    private void prepareStatements() {
        try {
            setVariable = db.prepareStatement("UPDATE sysvar SET value = ? WHERE name = ?");
            getVariable = db.prepareStatement("SELECT value FROM sysvar WHERE name = ?");
        } catch (SQLException ex) {
            Logger.getLogger(MySQLVariableDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * gets a varible from the database
     * @param variable the varible to be retrieved
     * @return a varible, else and empty string if the varible could not be retrieved
     */
    public String getVariable(String variable) {
        try {
            getVariable.setString(1, variable);

            ResultSet rs = getVariable.executeQuery();

            if (rs.next()) {
                return rs.getString(1);
            }

        } catch (SQLException ex) {
            Logger.getLogger(MySQLVariableDAO.class.getName()).log(Level.SEVERE, null, ex);
        }

        return "";
    }

    /**
     * updates a varible in the database
     * @param variable the new varible
     * @param value the new varible value
     */
    public void setVariable(String variable, String value) {
        try {
            setVariable.setString(1, value);
            setVariable.setString(2, variable);

            setVariable.execute();

        } catch (SQLException ex) {
            Logger.getLogger(MySQLVariableDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
